package com.sumainfor.common.util;


import com.alibaba.fastjson.JSONObject;
import com.google.common.reflect.TypeToken;
import com.sumainfor.common.Constants;
import okhttp3.*;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.*;
import java.util.*;

public class HttpUtilBee {
    private static Logger log = LoggerFactory.getLogger(InteSameCityUtil.class);// 日志
    private static int TIMEOUT = 10000;
    /**
     * 带参数的get请求,需要设置请求头
     * @param url
     * @return String
     */
    public static JSONObject doGet(String url,Map<String,Object> headerParam) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        JSONObject jsStr=null;
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);

            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            //设置请求头
            Iterator it=headerParam.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry entry = (Map.Entry)it.next();
                httpGet.addHeader(entry.getKey().toString(),entry.getValue().toString());
            }
        /*    httpGet.addHeader("version","0116010101");
            httpGet.addHeader("appid","57d7b05f6969600738d62682");*/
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String resultString= EntityUtils.toString(response.getEntity(), "UTF-8");
                jsStr = JSONObject.parseObject(resultString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsStr;
    }
    /**
     * 带参数的get请求,不需要设置请求头
     * @param url
     * @return String
     */
    public static JSONObject doGet(String url) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();


        JSONObject jsStr=null;
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);

            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
        /*    httpGet.addHeader("version","0116010101");
            httpGet.addHeader("appid","57d7b05f6969600738d62682");*/
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String resultString= EntityUtils.toString(response.getEntity(), "UTF-8");
                jsStr = JSONObject.parseObject(resultString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsStr;
    }
    /**
     * 带参数的post请求
     * @param url
     * @param param
     * @return String
     */
    public static JSONObject doPostParams(String url, Map<String, Object> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsStr=null;
        CloseableHttpResponse response = null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key).toString()));
                }
                System.out.println("paramList"+paramList);
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            jsStr = JSONObject.parseObject(resultString);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsStr;
    }
    /**
     * 传送json类型的post请求
     * @param url
     * @return String
     */
    public static JSONObject doPost(String url,Map<String, Object> param,JSONObject bodyJson) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        JSONObject jsStr=null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            //设置请求头
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("DataEncoding", "UTF-8");
            Iterator it=param.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry entry = (Map.Entry)it.next();
                httpPost.addHeader(entry.getKey().toString(),entry.getValue().toString());
            }
            // 创建请求内容
            StringEntity entity = new StringEntity(bodyJson.toString(), ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            jsStr = JSONObject.parseObject(resultString);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsStr;
    }
    /**
     * 传送json类型的post请求
     * @param url
     * @return String
     */
    public static JSONObject doPost(String url,Map<String, Object> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        JSONObject jsStr=null;
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            //设置请求头
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("DataEncoding", "UTF-8");
            Iterator it=param.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry entry = (Map.Entry)it.next();
                httpPost.addHeader(entry.getKey().toString(),entry.getValue().toString());
            }
      /*      // 创建请求内容
            StringEntity entity = new StringEntity(bodyJson.toString(), ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);*/
            // 执行http请求
            response = httpClient.execute(httpPost);
            String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            jsStr = JSONObject.parseObject(resultString);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsStr;
    }
    /**
     * @throws IOException
     * @throws ClientProtocolException
     *             *
     *******************************************************/
    public static String postResponse(String url, Map<String, String> parameters) throws ClientProtocolException, IOException {
        boolean ssl = url.startsWith("https://");

        // create the httpClientBuilder
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultRequestConfig(requestConfig);
        if (ssl) {
            SSLContextBuilder builder = new SSLContextBuilder();
            try {
                builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                httpClientBuilder.setSSLSocketFactory(sslsf);
            } catch (Exception e) {
                log.error("创建SSLcontext失败", e);
            }
        }

        CloseableHttpClient httpClient = httpClientBuilder.build();

        HttpPost method = new HttpPost(url);
        // ////////////////////////////////////////////
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // 建立一个NameValuePair数组，用于存储欲传送的参数
        if (parameters != null && parameters.size() > 0) {
            for (String key : parameters.keySet()) {
                params.add(new BasicNameValuePair(key, parameters.get(key)));
            }
        }
        // 添加参数
        method.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

        // 设置编码
        CloseableHttpResponse response = httpClient.execute(method);

        int statusCode = response.getStatusLine().getStatusCode();

        method.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        InputStreamReader reader = null;
        // CloseableHttpResponse httpResponse = null;
        try {

            if (response.getStatusLine().getStatusCode() != 200) {
                log.error(String.format("获取数据失败 \nurl = \"%s\" \nmethod = \"POST\" \nresponse code = \"%s\" \nreason = \"%s\"", method.getURI().toString(),
                        response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
                // return null;
            }
            reader = new InputStreamReader(response.getEntity().getContent());
            BufferedReader br = new BufferedReader(reader);
            String output = "";
            StringBuilder sbReturn = new StringBuilder();
            while ((output = br.readLine()) != null) {
                sbReturn.append(output);
            }

            return sbReturn.toString();

        } catch (Exception e) {
            log.error(String.format("获取数据失败  \nurl = \"%s\" \nmethod = \"POST\"", method.getURI().toString()), e);
        } finally {
            try {
                reader.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error("关闭POST请求失败", e);
                }
            }
        }

        return null;
    }
    /**
     * 发送put请求
     * @param url
     * @param headerParam
     * @return
     */
    public static JSONObject doPut(String url,Map<String, Object> headerParam) {
        JSONObject jsStr=null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpPut.setConfig(requestConfig);
        //设置请求头
        httpPut.setHeader("Content-type", "application/json");
        httpPut.setHeader("DataEncoding", "UTF-8");
        Iterator it=headerParam.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry entry = (Map.Entry)it.next();
            httpPut.setHeader(entry.getKey().toString(),entry.getValue().toString());
        }
/*        httpPut.setHeader("Content-type", "application/json");
        httpPut.setHeader("DataEncoding", "UTF-8");
        httpPut.setHeader("token", token);*/

        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpPut);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);

            jsStr = JSONObject.parseObject(result);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return jsStr;
    }

    /**
     * 发送put请求 并设置请求头和请求体
     * @param url
     * @param headerParam
     * @param bodyJson
     * @return
     */
    public static JSONObject doPut(String url,Map<String, Object> headerParam,JSONObject bodyJson) {
        JSONObject jsStr=null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpPut.setConfig(requestConfig);
        //设置请求头
        httpPut.setHeader("Content-type", "application/json");
        httpPut.setHeader("DataEncoding", "UTF-8");
        Iterator it=headerParam.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry entry = (Map.Entry)it.next();
            httpPut.setHeader(entry.getKey().toString(),entry.getValue().toString());
        }
        StringEntity se;
        CloseableHttpResponse httpResponse = null;
        try {
            //设置请求体
            se = new StringEntity(bodyJson.toString());
            se.setContentType("application/json");
            httpPut.setEntity(se);
            httpResponse = httpClient.execute(httpPut);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);

            jsStr = JSONObject.parseObject(result);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return jsStr;
    }
    /**
     * 发送put请求 并设置请求头和请求体
     * @param url
     * @param headerParam
     * @param bodyJson
     * @return
     */
    public static JSONObject doPut(String url,Map<String, Object> headerParam,String bodyJson) {
        JSONObject jsStr=null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpPut.setConfig(requestConfig);
        //设置请求头
        httpPut.setHeader("Content-type", "application/json");
        httpPut.setHeader("DataEncoding", "UTF-8");
        Iterator it=headerParam.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry entry = (Map.Entry)it.next();
            httpPut.setHeader(entry.getKey().toString(),entry.getValue().toString());
        }
        StringEntity se;
        CloseableHttpResponse httpResponse = null;
        try {
            //设置请求体
            se = new StringEntity(bodyJson);
            se.setContentType("application/json");
            httpPut.setEntity(se);
            httpResponse = httpClient.execute(httpPut);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);

            jsStr = JSONObject.parseObject(result);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return jsStr;
    }

    /**
     * 发送delete 请求
     * @param url
     * @param headerParam
     * @return
     */
    public static JSONObject doDelete(String url,Map<String, Object> headerParam) {
        JSONObject jsStr=null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpdel = new HttpDelete(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpdel.setConfig(requestConfig);
        //设置请求头
        httpdel.setHeader("Content-type", "application/json");
        httpdel.setHeader("DataEncoding", "UTF-8");
        Iterator it=headerParam.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry entry = (Map.Entry)it.next();
            httpdel.setHeader(entry.getKey().toString(),entry.getValue().toString());
        }
        StringEntity se;
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpdel);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);

            jsStr = JSONObject.parseObject(result);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return jsStr;
    }
    public static String post(String url,String xmlString){
        //关闭
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
        System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "stdout");

        //创建httpclient工具对象
        HttpClient client = new HttpClient();
        //创建post请求方法
        PostMethod myPost = new PostMethod(url);
        //设置请求超时时间
//                 client.setConnectionTimeout(300*1000);
        String responseString = null;
        try{
            //设置请求头部类型
            myPost.setRequestHeader("Content-Type","text/xml");
            myPost.setRequestHeader("charset","utf-8");

            //设置请求体，即xml文本内容，注：这里写了两种方式，一种是直接获取xml内容字符串，一种是读取xml文件以流的形式
            myPost.setRequestBody(xmlString);

//                         InputStream body=this.getClass().getResourceAsStream("/"+xmlFileName);
//                         myPost.setRequestBody(body);
            myPost.setRequestEntity(new StringRequestEntity(xmlString,"text/xml","utf-8"));
            int statusCode = client.executeMethod(myPost);
            if(statusCode == HttpStatus.SC_OK){
                BufferedInputStream bis = new BufferedInputStream(myPost.getResponseBodyAsStream());
                byte[] bytes = new byte[1024];
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                int count = 0;
                while((count = bis.read(bytes))!= -1){
                    bos.write(bytes, 0, count);
                }
                byte[] strByte = bos.toByteArray();
                responseString = new String(strByte,0,strByte.length,"utf-8");
                bos.close();
                bis.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        myPost.releaseConnection();
        return responseString;
    }
}
